package middlewares

import (
	"boy-go/pkg/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 全局异常处理
func ExceptionHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 打印堆栈信息（可用于日志记录）
				fmt.Printf("Panic recovered: %v\n", err)
				ajax := response.NewAjaxResult()
				ajax.SetCode(response.ServerError)
				ajax.SetMsg(fmt.Sprintf("服务器错误:%v", err))
				// 返回统一错误响应
				c.AbortWithStatusJSON(http.StatusInternalServerError, ajax.Result)
			}
		}()
		c.Next()
	}
}
